from flask import abort
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from info import create_app, db, models

# manage.py 是程序启动的入口,只关心启动的相关参数以及内容
# 通过指定的配置名字创建对应配置的app
# create_app() 工厂方法
from info.models import User

app = create_app("development")
manager = Manager(app)
# 将app和db关联
Migrate(app, db)
# 将迁移命令添加到manager中from flask import abort
from flask import current_app
from flask import g
from flask import session

from info import constants
from info.models import News, User
from info.modules.news import news_blu
from flask import render_template

from info.utils.common import user_login_data


@news_blu.route('/<int:news_id>')
@user_login_data
def news_detail(news_id):
    """
    新闻详情
    :param news_id:
    :return:
    """

    # 查询用户登录信息
    user = g.user

    # 右侧的新闻排行的逻辑
    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    # 定义一个空的字典列表，里面装的就是字典
    news_dict_li = []
    # 遍历对象列表，将对象的字典添加到字典列表中
    for news in news_list:
        news_dict_li.append(news.to_basic_dict())

    # 查询新闻数据
    news = None

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)

    if not news:
        # 报404错误，404错误统一显示页面后续再处理
        abort(404)

    # 更新新闻的点击次数
    news.clicks += 1

    data = {
        "user": user.to_dict() if user else None,
        "news_dict_li": news_dict_li,
        "news": news.to_dict()
    }

    return render_template("news/detail.html", data=data)


manager.add_command('db', MigrateCommand)


# 通过命令行创建管理员账号
@manager.option('-n', '-name', dest="name")
@manager.option('-p', '-password', dest="password")
def createsuperuser(name, password):

    if not all([name, password]):
        print("参数不足")

    user = User()
    user.nick_name = name
    user.mobile = name
    user.password = password
    user.is_admin = True

    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        print(e)
        # 运行方式
        # python manage.py createsuperuser -n admin -p 123456
    print("添加成功")


if __name__ == "__main__":
    # pycharm运行时,设置运行选项后加runserver
    manager.run()